extends NinePatchRect

var HP_scene: PackedScene
@export var HP_container: HBoxContainer
@export var HP_label: Label
@export var margin_container: MarginContainer

var max_hp: int
var left_hp: int

var HP_WIDTH = 5.0
var MAX_CONTAINER_WIDTH = 50.0
var GAP_WIDTH
var MARGIN_WIDTH = 2.0

func _ready():
	HP_scene = preload ("res://Piece/Character/enemy/UI/hp.tscn")
	GAP_WIDTH = HP_container.get_theme_constant("separation")

# 更新血量显示条
func update_hp_bar(max_hp_in: int, left_hp_in: int):
	max_hp = max_hp_in
	left_hp = left_hp_in

	# 设置文本显示
	HP_label.text = "%s/%s" % [left_hp, max_hp]

	# 先清空现有的血条
	var hp_children = HP_container.get_children()
	for child in hp_children:
		child.queue_free()
	
	# 设定container的长度
	var container_width = min((max_hp * HP_WIDTH) + (2 * MARGIN_WIDTH) + ((max_hp - 1) * GAP_WIDTH), MAX_CONTAINER_WIDTH)
	
	# 计算单个HP长度
	var hp_width = floor((container_width - (2 * MARGIN_WIDTH) - (max_hp - 1) * GAP_WIDTH) / max_hp)
	
	# 如果血量上上限较少，则一格格的显示
	if hp_width > 0:
		container_width = hp_width * max_hp + (max_hp - 1) * GAP_WIDTH + (2 * MARGIN_WIDTH)
		
		print("container_width: ", container_width)
		print("HP_width", hp_width)

		size.x = container_width
		
		for i in range(left_hp):
			var new_hp_node = HP_scene.instantiate()
			new_hp_node.custom_minimum_size.x = hp_width
			HP_container.add_child(new_hp_node)
	# 如果血量上限很多，则合并为一格显示
	else:
		size.x = MAX_CONTAINER_WIDTH
		var new_hp_node = HP_scene.instantiate()
		new_hp_node.custom_minimum_size.x = (MAX_CONTAINER_WIDTH - (2 * MARGIN_WIDTH)) * ((left_hp * 1.0) / (max_hp * 1.0))
		HP_container.add_child(new_hp_node)

	position = Vector2( - 1 * (container_width / 2.0), 40)
		